<template>
  <div>
    <el-dialog v-model="props.networkVisible" title="网络配置" draggable @close="handleNetworkClose">
      <el-button type="primary" @click="handleTong(1)">新增</el-button>
      <el-button type="danger" @click="handleTong(2)">删除</el-button>

      <el-table :data="networkList" height="500" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="rowSelectable" />
        <el-table-column prop="serverId" label="站点服务器ID" width="150"/>
        <el-table-column prop="ipAddress" label="IP" />
        <el-table-column prop="newType" label="类型" align="center" />
        <el-table-column prop="serverNo" label="状态" align="center">
          <template #default="scope">
            <el-switch :width="58" v-model="scope.row.status" :active-value="1" :inactive-value="0" active-text="开启"
              inactive-text="关闭" inline-prompt @change="switchProcess(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleTong(0, scope.row)">编辑</el-button>

            <el-button link type="danger" @click="handleTong(3, scope.row)" v-if="!scope.row.status">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :total="total" :limit="searchFrom.pageSize" :page="searchFrom.pageNum"
        @pagination="handleCurrentChange">
      </Pagination>

      <el-dialog v-model="drawer" :title="title" width="550" :before-close="handleClose">
        <el-form :inline="true" :model="submitFrom" label-width="auto" ref="SiteIpRef" :rules="rules"
          label-position="left">
          <el-form-item label="站点服务器ID" prop="serverId" style="width: 100%" required>
            <el-input v-model.trim="submitFrom.serverId" disabled />
          </el-form-item>
          <el-form-item label="类型" prop="ipType" style="width: 100%" required>
            <el-select v-model="submitFrom.ipType" placeholder="请选择" @change="changeIpType">
              <el-option v-for="(dict, index) in sys_server_type" :key="index" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label=" " v-if="showRadio">
            <el-radio-group v-model="submitFrom.isIpRange" @change="changeRadio">
              <el-radio :value="false">IP</el-radio>
              <el-radio :value="true" :disabled="showDisabled">IP段</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="IP地址" prop="newIpAddress" style="width: 100%" required>
            <el-input v-model.trim="submitFrom.newIpAddress" placeholder="请输入" v-if="!submitFrom.isIpRange" />
            <el-space spacer="-" v-else>
              <el-input v-model.trim="submitFrom.newIpAddress" placeholder="请输入" style="width: 300px;" />
              <el-input-number controls-position="right" :min="0" :max="255" v-model="submitFrom.IpGroup"
                style="width: calc(100% - 310px);" />
            </el-space>
          </el-form-item>
          <el-form-item label="状态" prop="status" required>
            <el-switch :width="58" v-model="submitFrom.status" :inactive-value="0" :active-value="1" active-text="开启"
              inactive-text="关闭" inline-prompt />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSure"> 确定 </el-button>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, reactive } from "vue";
const emits = defineEmits(["handleNetworkClose"]);
const { proxy } = getCurrentInstance();
const deleteIds = ref([]);
const drawer = ref(false);
const title = ref("");
const switchLoading = ref(true);
const { sys_server_type } = proxy.useDict("sys_server_type"); //服务器IP类型
const publicItem = ref({}); //公共赋值数据
const total = ref(0);
const networkList = ref([]);
const showRadio = ref(false)//默认不显示
const showDisabled = ref(true)//默认显示true
const submitFrom = ref({
  serverId: null, //站点服务器ID
  ipType: "", //类型
  ipAddress: "", //IP地址,提交进行拼接
  status: 1, //状态
  used: true, //正在使用的
  isIpRange: null,

  newIpAddress: '',//IP地址
  IpGroup: null
}); //提交参数

const props = defineProps({
  networkVisible: {
    type: Boolean,
    default: false,
  },
  // 传值数据对象
  listItem: {
    type: Object,
    default: {},
  },
});
const searchFrom = ref({
  pageNum: 1,
  pageSize: 20,
  param: {
    serverId: null, //服务器id
  },
}); //搜索参数
onMounted(() => { });
watch(
  () => props.networkVisible,
  () => {
    deleteIds.value = []; //勾选的id制空
    if (!props.networkVisible) return;
    searchFrom.value.param.serverId = props.listItem.id;
    getList();
  }
);
const getList = () => {
  site.ip
    .siteserveriprangeList({
      data: searchFrom.value,
    })
    .then((res) => {
      switchLoading.value = false;
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            newType: sys_server_type.value.find((e) => e.value === code.ipType)
              ?.label,
          };
        });
      }
      networkList.value = res.data;
      total.value = res.total;
    })
    .catch((err) => { });
};

// 取消事件
const handleNetworkClose = () => {
  emits("handleNetworkClose");
};
// 分页
const handleCurrentChange = (newPage) => {
  searchFrom.value.pageNum = newPage.page;
  searchFrom.value.pageSize = newPage.limit;
  getList();
};
const handleTong = (index, rowItem) => {
  if (index === 1) {
    publicItem.value = [];
    // 新增
    title.value = "新增";
    drawer.value = true;
    submitFrom.value.serverId = props.listItem.id;
  } else if (index === 2) {
    // 删除多选的id
    deleteAssemble(deleteIds.value);
  } else if (index === 3) {
    let newListId = [];
    newListId.push(rowItem.id);
    // 删除选中的id
    deleteAssemble(newListId);
  } else {
    // 编辑
    site.ip.siteserveriprangeGetbyid({
      pathParams: {
        id: rowItem.id
      }
    }).then((res) => {
      if (res.code == 200) {
        console.log(res.data, '详情');
        title.value = "编辑";
        submitFrom.value.serverId = res.data.serverId;
        submitFrom.value.ipType = res.data.ipType;
        submitFrom.value.status = res.data.status;
        submitFrom.value.serverId = res.data.serverId;
        submitFrom.value.used = res.data.used;
        publicItem.value = res.data;
        if (res.data.ipAddress.includes('-')) {
          submitFrom.value.newIpAddress = res.data.ipAddress.split('-')[0]
        } else {
          submitFrom.value.newIpAddress = res.data.ipAddress;
        }
        drawer.value = true;
      }
    });

  }
};
const handleSure = () => {
  proxy.$refs["SiteIpRef"].validate((valid) => {
    if (valid) {
      if (Object.keys(publicItem.value).length) {
        site.ip
          .siteserveriprangeUpdatebyid({
            pathParams: {
              id: publicItem.value.id,
            },
            data: submitFrom.value,
          })
          .then((res) => {
            if (res.code !== 200) return;
            getList();
            proxy.$modal.msgSuccess("修改成功");
            handleClose();
          });
      } else {
        let pattern = /^(0|[1-9]\d*)$/;// 正则校验正整数
        if (submitFrom.value.isIpRange) {
          if (!pattern.test(submitFrom.value.IpGroup)) return proxy.$modal.msgWarning("IP字段组只能是正整数")
          let lastPart = submitFrom.value.newIpAddress.match(/\.([^\.]+)$/)[1];
          if (submitFrom.value.IpGroup < lastPart) return proxy.$modal.msgWarning("IP字段组必须大于IP最后一位")
          submitFrom.value.ipAddress = `${submitFrom.value.newIpAddress}-${submitFrom.value.IpGroup}`;
        } else {
          submitFrom.value.ipAddress = submitFrom.value.newIpAddress
        }
        site.ip
          .siteserveriprangeAdd({
            data: submitFrom.value,
          })
          .then((res) => {
            if (res.code !== 200) return;
            getList();
            proxy.$modal.msgSuccess("新增成功");
            handleClose();
          });
      }
    }
  });
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  deleteIds.value = selection.map((item) => item.id);
};
const rowSelectable = (row) => {
  return row.status !== 1;
};
const handleClose = () => {
  drawer.value = false;
  proxy.resetForm("SiteIpRef");
  submitFrom.value.serverId = "";
  submitFrom.value.ipType = "";
  submitFrom.value.newIpAddress = "";
  submitFrom.value.status = 1;
  submitFrom.value.used = true;
  submitFrom.value.isIpRange = false
  submitFrom.value.IpGroup = null
  showRadio.value = false
};
const deleteAssemble = (List) => {
  if (!List.length) return proxy.$modal.msgWarning("请勾选");
  proxy.$modal.confirm(`是否确认删除此数据`).then(() => {
    site.ip
      .siteserveriprangeRemovebatchbyids({
        data: {
          ids: List,
        },
      })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$modal.msgSuccess("修改成功");
        }
      });
  });
};

const switchProcess = (rowItem) => {
  if (switchLoading.value) return;
  proxy.$modal
    .confirm("是否确认修改此数据类型？")
    .then(() => {
      site.ip
        .siteserveriprangeUpdate_status({
          pathParams: {
            id: rowItem.id,
          },
          params: {
            status: rowItem.status,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            getList();
            proxy.$modal.msgSuccess(res.message);
          }
        })
        .catch((err) => {
          if (rowItem.status) {
            return (rowItem.status = 0);
          } else {
            return (rowItem.status = 1);
          }
        });
    })
    .catch((err) => {
      if (rowItem.status) {
        return (rowItem.status = 0);
      } else {
        return (rowItem.status = 1);
      }
    });
};
const changeIpType = (e) => {
  if (title.value === '编辑') return
  showRadio.value = true
  if (e === 'MAIN') {
    showDisabled.value = true
    submitFrom.value.IpGroup = null
  } else {
    showDisabled.value = false
  }
  submitFrom.value.isIpRange = false
}
const changeRadio = (e) => {
  if (!e) return submitFrom.value.IpGroup = null
}
const rules = reactive({
  serverId: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^\d+$/,
      message: "只能输入数字",
      trigger: "blur",
    },
  ],
  ipType: [{ required: true, message: "请选择", trigger: "blur" }],
  newIpAddress: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern:
        /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: "请正确输入ip地址",
      trigger: "blur",
    },
  ],
});
</script>